import { check, checkError, getRequest } from "./baseUtils"

/**
 * 数据结构
 * 	Category 
 * 	  name: string
 * 	  description: string
 * 	  products: Product[]
 *   
 * 	Prodcut
 *    id: string					商品ID
 *    name: string					名称
 * 	  description: string			描述
 *    currentPrice: number			现价
 *    originalPrice: number			原价
 *    monthlySales: number			月销售
 *    count: number					数量（搭配购物车）
 *    image: string					图片链接
 *    tags: string[]				标签
 * 
 * Api 方法
 * static getAll()                  获取所有数据
 */
class CategoryApi {

    static baseUrl = '/category'
	
	static async getAll() {
		uni.showLoading({title: "加载中", mask: true})
		try {
			const response = await uni.request(getRequest({url: this.baseUrl, method: "GET"}))
			return check(response)
		} 
		catch(error) { checkError(error) }
		finally { uni.hideLoading() }
	}

}

const key = "categories"

export class CategoryUtils {
	
	static getAll(success) {
		// 如果缓存中不存在，则去后台请求
		const categories = uni.getStorageSync(key)
		if (!categories) {
			// 不存在，去后台请求
			CategoryApi.getAll()
			.then(data => {
				uni.setStorageSync(key, data)
				success(data)
			})
		} 
		else {
			success(categories)
		}
	}
	
	static reload(success) {
		CategoryApi.getAll()
		.then(data => {
			uni.setStorageSync(key, data)
			success(data)
		})
	}
	
	static clear() {
		uni.removeStorageSync(key)
	}
	
}